<template>
  <div class="template-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h2 class="page-title">
          <el-icon><Document /></el-icon>
          消息模版
        </h2>
        <p class="page-subtitle">管理和配置系统消息模板</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="createTemplate">
          <el-icon><Plus /></el-icon>
          新建模板
        </el-button>
        <el-button @click="refreshTemplates">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card total-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ templateStats.total }}</div>
              <div class="stat-label">总模板数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card active-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Check /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ templateStats.active }}</div>
              <div class="stat-label">启用模板</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card system-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Setting /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ templateStats.system }}</div>
              <div class="stat-label">系统模板</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card custom-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Edit /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ templateStats.custom }}</div>
              <div class="stat-label">自定义模板</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索和筛选 -->
    <el-card class="search-card" shadow="hover">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索模板名称或内容"
            clearable
            style="width: 200px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="模板类型">
          <el-select v-model="searchForm.type" placeholder="选择模板类型" clearable style="width: 150px">
            <el-option label="系统通知" value="system" />
            <el-option label="工作通知" value="work" />
            <el-option label="个人消息" value="personal" />
            <el-option label="公告消息" value="announcement" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="选择状态" clearable style="width: 120px">
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 模板列表 -->
    <el-card class="template-list-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>模板列表</span>
          <div class="header-actions">
            <el-button type="danger" @click="batchDelete" :disabled="selectedTemplates.length === 0">
              <el-icon><Delete /></el-icon>
              批量删除
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="templateList"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="模板名称" min-width="150">
          <template #default="{ row }">
            <div class="template-name">
              <el-icon v-if="row.isSystem" class="system-icon"><Setting /></el-icon>
              <span>{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)" size="small">
              {{ getTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.isActive ? 'success' : 'info'" size="small">
              {{ row.isActive ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="usageCount" label="使用次数" width="100" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="editTemplate(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button 
              :type="row.isActive ? 'warning' : 'success'" 
              size="small" 
              @click="toggleTemplateStatus(row)"
              :disabled="row.isSystem"
            >
              <el-icon><Check /></el-icon>
              {{ row.isActive ? '禁用' : '启用' }}
            </el-button>
            <el-button type="info" size="small" @click="previewTemplate(row)">
              <el-icon><View /></el-icon>
              预览
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="deleteTemplate(row)"
              :disabled="row.isSystem"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 模板编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="isEdit ? '编辑模板' : '新建模板'"
      width="800px"
      :before-close="handleCloseEdit"
    >
      <el-form
        ref="templateFormRef"
        :model="templateForm"
        :rules="templateRules"
        label-width="100px"
      >
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="templateForm.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板类型" prop="type">
          <el-select v-model="templateForm.type" placeholder="选择模板类型" style="width: 100%">
            <el-option label="系统通知" value="system" />
            <el-option label="工作通知" value="work" />
            <el-option label="个人消息" value="personal" />
            <el-option label="公告消息" value="announcement" />
          </el-select>
        </el-form-item>
        <el-form-item label="模板描述" prop="description">
          <el-input
            v-model="templateForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入模板描述"
          />
        </el-form-item>
        <el-form-item label="模板内容" prop="content">
          <el-input
            v-model="templateForm.content"
            type="textarea"
            :rows="8"
            placeholder="请输入模板内容，可使用变量：{{userName}}、{{date}}、{{time}}等"
          />
        </el-form-item>
        <el-form-item label="变量说明">
          <div class="variable-help">
            <p>可用的变量：</p>
            <ul>
              <li><code>\{\{userName\}\}</code> - 用户名</li>
              <li><code>\{\{date\}\}</code> - 当前日期</li>
              <li><code>\{\{time\}\}</code> - 当前时间</li>
              <li><code>\{\{company\}\}</code> - 公司名称</li>
              <li><code>\{\{department\}\}</code> - 部门名称</li>
            </ul>
          </div>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="templateForm.isActive"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveTemplate">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 模板预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="模板预览"
      width="600px"
    >
      <div v-if="currentPreviewTemplate" class="template-preview">
        <div class="preview-header">
          <h3>{{ currentPreviewTemplate.name }}</h3>
          <el-tag :type="getTypeTagType(currentPreviewTemplate.type)" size="small">
            {{ getTypeLabel(currentPreviewTemplate.type) }}
          </el-tag>
        </div>
        <div class="preview-content">
          <h4>模板内容：</h4>
          <div class="content-display">{{ currentPreviewTemplate.content }}</div>
        </div>
        <div class="preview-variables">
          <h4>变量示例：</h4>
          <div class="variables-display">
            <p><strong>userName:</strong> 张三</p>
            <p><strong>date:</strong> 2024-12-01</p>
            <p><strong>time:</strong> 14:30:00</p>
            <p><strong>company:</strong> RBAC科技有限公司</p>
            <p><strong>department:</strong> 技术部</p>
          </div>
        </div>
        <div class="preview-result">
          <h4>预览效果：</h4>
          <div class="result-display">
            {{ getPreviewResult(currentPreviewTemplate.content) }}
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import {
  Document,
  Plus,
  Refresh,
  Check,
  Setting,
  Edit,
  Search,
  Delete,
  View
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const editDialogVisible = ref(false)
const previewDialogVisible = ref(false)
const isEdit = ref(false)
const selectedTemplates = ref<any[]>([])
const currentPreviewTemplate = ref<any>(null)
const templateFormRef = ref<FormInstance>()

// 搜索表单
const searchForm = reactive({
  keyword: '',
  type: '',
  status: ''
})

// 分页配置
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 模板统计数据
const templateStats = reactive({
  total: 0,
  active: 0,
  system: 0,
  custom: 0
})

// 模板表单
const templateForm = reactive({
  id: '',
  name: '',
  type: '',
  description: '',
  content: '',
  isActive: true
})

// 表单验证规则
const templateRules: FormRules = {
  name: [
    { required: true, message: '请输入模板名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择模板类型', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入模板内容', trigger: 'blur' },
    { min: 10, message: '内容至少 10 个字符', trigger: 'blur' }
  ]
}

// 模板列表数据
const templateList = ref([
  {
    id: 'TPL001',
    name: '系统维护通知',
    type: 'system',
    description: '系统维护时的通知模板',
    content: '尊敬的用户，系统将于{{date}} {{time}}进行维护，预计维护时间2小时，期间可能影响正常使用，请提前做好准备。',
    createTime: '2024-11-01 10:00:00',
    isActive: true,
    isSystem: true,
    usageCount: 15
  },
  {
    id: 'TPL002',
    name: '工作安排通知',
    type: 'work',
    description: '工作安排和会议通知模板',
    content: '各位同事，{{date}} {{time}}将召开{{department}}会议，请准时参加。会议地点：会议室A，会议主题：{{meetingTopic}}。',
    createTime: '2024-11-05 14:30:00',
    isActive: true,
    isSystem: false,
    usageCount: 8
  },
  {
    id: 'TPL003',
    name: '请假审批通知',
    type: 'personal',
    description: '请假申请审批结果通知',
    content: '{{userName}}，您的请假申请已{{approvalResult}}。申请时间：{{leaveDate}}，请假天数：{{leaveDays}}天。',
    createTime: '2024-11-10 09:15:00',
    isActive: true,
    isSystem: false,
    usageCount: 12
  },
  {
    id: 'TPL004',
    name: '公司公告模板',
    type: 'announcement',
    description: '公司重要公告发布模板',
    content: '{{company}}公告：{{announcementTitle}}。详情请查看附件或联系相关部门。发布时间：{{date}} {{time}}。',
    createTime: '2024-11-15 16:45:00',
    isActive: false,
    isSystem: false,
    usageCount: 3
  }
])

// 方法
const getTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    system: '系统通知',
    work: '工作通知',
    personal: '个人消息',
    announcement: '公告消息'
  }
  return typeMap[type] || type
}

const getTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    system: 'danger',
    work: 'primary',
    personal: 'success',
    announcement: 'warning'
  }
  return typeMap[type] || 'info'
}

const handleSearch = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    ElMessage.success('搜索完成')
  }, 1000)
}

const resetSearch = () => {
  Object.assign(searchForm, {
    keyword: '',
    type: '',
    status: ''
  })
  handleSearch()
}

const handleSelectionChange = (selection: any[]) => {
  selectedTemplates.value = selection
}

const createTemplate = () => {
  isEdit.value = false
  resetTemplateForm()
  editDialogVisible.value = true
}

const editTemplate = (template: any) => {
  isEdit.value = true
  Object.assign(templateForm, {
    id: template.id,
    name: template.name,
    type: template.type,
    description: template.description,
    content: template.content,
    isActive: template.isActive
  })
  editDialogVisible.value = true
}

const saveTemplate = async () => {
  if (!templateFormRef.value) return
  
  await templateFormRef.value.validate((valid) => {
    if (valid) {
      if (isEdit.value) {
        // 编辑模板
        const index = templateList.value.findIndex(tpl => tpl.id === templateForm.id)
        if (index > -1) {
          Object.assign(templateList.value[index], {
            name: templateForm.name,
            type: templateForm.type,
            description: templateForm.description,
            content: templateForm.content,
            isActive: templateForm.isActive
          })
        }
        ElMessage.success('模板更新成功')
      } else {
        // 新建模板
        const newTemplate = {
          id: `TPL${Date.now()}`,
          name: templateForm.name,
          type: templateForm.type,
          description: templateForm.description,
          content: templateForm.content,
          createTime: new Date().toLocaleString(),
          isActive: templateForm.isActive,
          isSystem: false,
          usageCount: 0
        }
        templateList.value.unshift(newTemplate)
        ElMessage.success('模板创建成功')
      }
      editDialogVisible.value = false
      updateTemplateStats()
    }
  })
}

const handleCloseEdit = () => {
  editDialogVisible.value = false
  resetTemplateForm()
}

const resetTemplateForm = () => {
  Object.assign(templateForm, {
    id: '',
    name: '',
    type: '',
    description: '',
    content: '',
    isActive: true
  })
}

const toggleTemplateStatus = (template: any) => {
  template.isActive = !template.isActive
  updateTemplateStats()
  ElMessage.success(template.isActive ? '模板已启用' : '模板已禁用')
}

const previewTemplate = (template: any) => {
  currentPreviewTemplate.value = template
  previewDialogVisible.value = true
}

const getPreviewResult = (content: string) => {
  return content
    .replace(/{{userName}}/g, '张三')
    .replace(/{{date}}/g, '2024-12-01')
    .replace(/{{time}}/g, '14:30:00')
    .replace(/{{company}}/g, 'RBAC科技有限公司')
    .replace(/{{department}}/g, '技术部')
    .replace(/{{meetingTopic}}/g, '项目进度讨论')
    .replace(/{{approvalResult}}/g, '通过')
    .replace(/{{leaveDate}}/g, '2024-12-15')
    .replace(/{{leaveDays}}/g, '3')
    .replace(/{{announcementTitle}}/g, '关于调整工作时间的通知')
}

const deleteTemplate = (template: any) => {
  ElMessageBox.confirm('确定要删除这个模板吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = templateList.value.findIndex(tpl => tpl.id === template.id)
    if (index > -1) {
      templateList.value.splice(index, 1)
      updateTemplateStats()
      ElMessage.success('删除成功')
    }
  })
}

const batchDelete = () => {
  if (selectedTemplates.value.length === 0) {
    ElMessage.warning('请选择要删除的模板')
    return
  }
  
  ElMessageBox.confirm(`确定要删除选中的 ${selectedTemplates.value.length} 个模板吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const ids = selectedTemplates.value.map(tpl => tpl.id)
    templateList.value = templateList.value.filter(tpl => !ids.includes(tpl.id))
    selectedTemplates.value = []
    updateTemplateStats()
    ElMessage.success('批量删除成功')
  })
}

const refreshTemplates = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    updateTemplateStats()
    ElMessage.success('刷新完成')
  }, 1000)
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  handleSearch()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  handleSearch()
}

const updateTemplateStats = () => {
  templateStats.total = templateList.value.length
  templateStats.active = templateList.value.filter(tpl => tpl.isActive).length
  templateStats.system = templateList.value.filter(tpl => tpl.isSystem).length
  templateStats.custom = templateList.value.filter(tpl => !tpl.isSystem).length
}

// 生命周期
onMounted(() => {
  updateTemplateStats()
})
</script>

<style scoped lang="less">
.template-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  .header-content {
    .page-title {
      display: flex;
      align-items: center;
      gap: 10px;
      margin: 0 0 8px 0;
      font-size: 24px;
      font-weight: 600;
      color: #303133;

      .el-icon {
        font-size: 28px;
        color: #409eff;
      }
    }

    .page-subtitle {
      margin: 0;
      color: #909399;
      font-size: 14px;
    }
  }

  .header-actions {
    display: flex;
    gap: 10px;
  }
}

.stats-row {
  margin-bottom: 20px;

  .stat-card {
    .stat-content {
      display: flex;
      align-items: center;
      gap: 15px;

      .stat-icon {
        width: 50px;
        height: 50px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24px;
        color: white;
      }

      .stat-info {
        .stat-value {
          font-size: 24px;
          font-weight: 600;
          color: #303133;
          line-height: 1;
        }

        .stat-label {
          font-size: 14px;
          color: #909399;
          margin-top: 4px;
        }
      }
    }

    &.total-card .stat-icon {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }

    &.active-card .stat-icon {
      background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    }

    &.system-card .stat-icon {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    }

    &.custom-card .stat-icon {
      background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
    }
  }
}

.search-card {
  margin-bottom: 20px;

  .search-form {
    margin: 0;
  }
}

.template-list-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .template-name {
    display: flex;
    align-items: center;
    gap: 8px;

    .system-icon {
      color: #409eff;
      font-size: 14px;
    }
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.variable-help {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
  border-left: 4px solid #409eff;

  p {
    margin: 0 0 10px 0;
    font-weight: 600;
    color: #303133;
  }

  ul {
    margin: 0;
    padding-left: 20px;

    li {
      margin-bottom: 5px;
      color: #606266;

      code {
        background-color: #e9ecef;
        padding: 2px 6px;
        border-radius: 3px;
        font-family: 'Courier New', monospace;
        color: #e83e8c;
      }
    }
  }
}

.template-preview {
  .preview-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;

    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }
  }

  .preview-content,
  .preview-variables,
  .preview-result {
    margin-bottom: 20px;

    h4 {
      margin: 0 0 10px 0;
      font-size: 14px;
      font-weight: 600;
      color: #303133;
    }
  }

  .content-display,
  .result-display {
    background-color: #f8f9fa;
    padding: 15px;
    border-radius: 6px;
    border: 1px solid #e9ecef;
    line-height: 1.6;
    color: #606266;
  }

  .variables-display {
    background-color: #f8f9fa;
    padding: 15px;
    border-radius: 6px;
    border: 1px solid #e9ecef;

    p {
      margin: 0 0 5px 0;
      color: #606266;

      strong {
        color: #303133;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .template-container {
    padding: 10px;
  }

  .page-header {
    flex-direction: column;
    gap: 15px;
    text-align: center;

    .header-actions {
      width: 100%;
      justify-content: center;
    }
  }

  .stats-row {
    .el-col {
      margin-bottom: 10px;
    }
  }

  .search-form {
    .el-form-item {
      margin-bottom: 10px;
    }
  }
}
</style>
